import { App, Component, createApp, ref, watch } from "vue"

import message from "./message"

interface Options {
    duration?: number,
    icon?: string,
    message?: string,
    type?: string
}

// let timer: null | undefined | number = null //防抖

let vnodeChildren = ref<any>([])

const types = ["success", "info", "warning", "error"] as const

export const Message: any = (options: Options) => {
    // console.log(options)
    const vnode = createApp(message, { ...options })
    showMessage(vnode, options.duration!)
}


//显示消息
const showMessage = (app: App, duration: number) => {

    const oFrag = document.createDocumentFragment()
    let vm: Component = app.mount(oFrag)
    vnodeChildren.value.push(vm) // 每次显示消息是记录一下
    // console.log(vm,"vm")
   
    document.body.appendChild(oFrag)
    setTopHeight(vm)
    vm.setVisible(true)
    watch(vnodeChildren,()=>setTopHeight(vm))
    hideMessage(app, vm, duration)
}

//隐藏消息
const hideMessage = (app: App, vm: any, duration: number) => {
    // console.log("关闭消息")
    vm.timer = setTimeout(async () => {
        await vm.setVisible(false)
        app.unmount()
        vnodeChildren.value = vnodeChildren.value.filter((item:typeof vm)=>item !=vm)
        clearTimeout(vm.timer as any)
        vm.timer = null
    }, duration || 3000)
}

//设置高度
const setTopHeight = (vm:any)=>{
    let {setTop,height,margin} = vm
    let currentIndex = vnodeChildren.value.findIndex((item:typeof vm)=>item==vm)
    setTop(margin*(currentIndex+1)+height*currentIndex)
}

//让message有message.success这样的函数调用
types.forEach(type => {
    Message[type] = (options: Options) => {
        return Message(options)
    }
});



